/**
 * 
 */
package com.cnhaimei.vod.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.Enumeration;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Process;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.cnhaimei.base.ApplicationEx;
import com.cnhaimei.vod.net.NetManager;

/**
 * @author jin001.wu@gmail.com <br>
 * @date 2011-7-24
 * 
 */
public class Util {
	public static final String FILE = "/v8/star_images/";
	public static final String LOG_FILE = "/v8/logs_1_0_0.log";
	public static final String FILE_SUB = ".jpg";
	public static final boolean DEMO = false;
	public static final boolean TEST = false;
	public static final boolean DEBUG = false;
	public static final boolean VLOG = true;
	public static Bitmap DEFAULT_STAR = null;
	public static String CUR_ROOM;
	public static ApplicationEx mApp;
	public static final String CONFIG_NAME = "VodConfig";

	public static int readInt(InputStream iStream) {
		int rtn = 0;
		byte[] readInt = new byte[4];
		try {
			Arrays.fill(readInt, (byte) 0);
			iStream.read(readInt, 0, readInt.length);
			rtn = (readInt[3] & 0xff);
			rtn = (rtn << 8) + (readInt[2] & 0xff);
			rtn = (rtn << 8) + (readInt[1] & 0xff);
			rtn = (rtn << 8) + (readInt[0] & 0xff);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return rtn;
	}

	public static int readInt(byte[] b, int offset) {
		int rtn = 0;
		rtn = (b[offset + 3] & 0xff);
		rtn = (rtn << 8) + (b[offset + 2] & 0xff);
		rtn = (rtn << 8) + (b[offset + 1] & 0xff);
		rtn = (rtn << 8) + (b[offset] & 0xff);
		return rtn;
	}

	public static String readString(byte[] bs, int begin, String encoding) {
		int byteCount = bs.length - begin;
		for (int i = begin; i < bs.length; i++) {
			if (bs[i] == 0) {
				byteCount = i - begin;
				break;
			}
		}

		String rtn = "";

		try {
			rtn = new String(bs, begin, byteCount, encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return rtn;
	}

	public static int parseInt(String s) {
		int rtn = 0;
		try {
			rtn = Integer.getInteger(s);
		} catch (NumberFormatException ne) {
			// exception;
		}

		return rtn;
	}

	public static Bitmap loadStar(String name) {

		File dic = Environment.getExternalStorageDirectory();
		String file = dic.getAbsolutePath() + FILE + name + FILE_SUB;
		Bitmap b = null; 
		try {
			b = BitmapFactory.decodeFile(file);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		if (b == null) {
			b = DEFAULT_STAR;
		}

		return b;
	}
	
	public static void exit() {
		NetManager.G().closeAll();
		Process.killProcess(Process.myPid());
	}
	
	public static void setIsFirstLaunch(Context context, boolean isFirstLaunch) {
		SharedPreferences settingPreferences = context.getSharedPreferences(CONFIG_NAME, 0);
		SharedPreferences.Editor editor = settingPreferences.edit();
		editor.putBoolean("isFirstLaunch", isFirstLaunch);
		editor.commit();
	}

	public static boolean getIsFirstLaunch(Context context) {
		SharedPreferences settingPreferences = context.getSharedPreferences(CONFIG_NAME, 0);
		return settingPreferences.getBoolean("isFirstLaunch", true);
	}
	
	public static void showMyToast(Context context, String strMsg, int duration)
	{
		Toast toast = Toast.makeText(context, strMsg, duration);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	public static void showMyToastEx(Context context, String strMsg, int duration)
	{
		Toast toast = Toast.makeText(context, strMsg, duration);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	
	private static String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." +
				((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
	}
	
	public static String getLocalIp(Context context) {
		WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
		if (!wifiManager.isWifiEnabled()) {
			return "";
		}
		
		WifiInfo info = wifiManager.getConnectionInfo();
		int ipAddress = info.getIpAddress();
		String strIp = intToIp(ipAddress);
		return strIp;
	}
	
	public static String getBroadcastIp(Context context) {
		String strIp = getLocalIp(context);
		if (strIp.length() > 0) {
//			int index = strIp.lastIndexOf('.');
//			if (index > 0) {
//				strIp = strIp.substring(0, index).concat(".255");
//				return strIp;
//			}
			int index = strIp.indexOf('.');
			if (index > 0) {
				strIp = strIp.substring(0, index).concat(".255.255.255");
				return strIp;
			}
		}
		
		return "";
	}

	public static String getBroadcastIp2(Context context) {
		String strIp = "255.255.255.255";
		
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (InterfaceAddress address : intf.getInterfaceAddresses()) {
					if (address != null && address.getBroadcast() != null) {
						strIp = address.getBroadcast().toString().substring(1);
						System.out.println(strIp);	
					}			 
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			 System.out.println(e.getMessage());	
		}
		
		return strIp;
	}
	
	public static int getDownloadedPackageCount() {
		int nSize = 0;
		try {
			File dic = Environment.getExternalStorageDirectory();
			String sdcardPath = dic.getAbsolutePath();
			String rootPath = sdcardPath + "/v8/";
			String localConfigPath = rootPath + "config";
			File rootFile = new File(rootPath);
			rootFile.mkdir();
			
			BufferedReader reader = new BufferedReader(new FileReader(localConfigPath));
			String strValue = reader.readLine();
			nSize = Integer.valueOf(strValue);
			reader.close();						
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return nSize;
	}

	public static void setDownloadedPackageCount(int nCount) {
		try {
			File dic = Environment.getExternalStorageDirectory();
			String sdcardPath = dic.getAbsolutePath();
			String rootPath = sdcardPath + "/v8/";
			String localConfigPath = rootPath + "config";
			File rootFile = new File(rootPath);
			rootFile.mkdir();

			BufferedWriter writer = new BufferedWriter(new FileWriter(localConfigPath));
			String strValue = String.valueOf(nCount);
			writer.write(strValue);
			writer.close();					
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void deleteFile(String strFilePath) {
		File file = new File(strFilePath);
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} 
			else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					deleteFile(files[i].getPath()); // 把每个文件 用这个方法进行迭代
				}
			}
				file.delete();
			} 
		else {
			Log.e("Util.deleteFile", "文件不存在！");
		}	
	}
}
